<template>
  <view class="my_modify">
    <form @submit.prevent="formSubmit">
      <view class="modify_container" @click="changeAvatar">
        <view class="modify_describe">头像：</view>
        <view class="modify_img">
          <image :src="avatarUrl" mode="aspectFill"></image>
        </view>
      </view>
      <view class="modify_container">
        <view class="modify_describe">昵称：</view>
        <view>
          <input type="text" name="userName" :value="userinfo.userName" placeholder="请输入昵称" />
        </view>
      </view>
      <view class="modify_container">
        <view class="modify_describe">性别：</view>
        <view>
          <input type="text" name="userGender" :value="userinfo.userGender" placeholder="请输入性别" />
        </view>
      </view>
      <view class="modify_container">
        <view class="modify_describe">体重：</view>
        <view>
          <input type="text" name="userWeight" :value="userinfo.userWeight" placeholder="请输入体重" />
        </view>
      </view>
      <view class="modify_container">
        <view class="modify_describe">体脂率：</view>
        <view>
          <input type="text" name="userBMI" :value="userinfo.userBMI" placeholder="请输入体脂率" />
        </view>
      </view>
      <view class="modify_container">
        <view class="modify_describe">邮箱：</view>
        <view>
          <input type="text" name="userEmail" :value="userinfo.userEmail" placeholder="请输入邮箱" />
        </view>
      </view>
      <view class="modify_container">
        <view class="modify_describe">手机号：</view>
        <view>
          <input type="text" name="userPhoneNumber" :value="userinfo.userPhoneNumber" placeholder="请输入手机号" />
        </view>
      </view>
      <view class="modify_container">
        <view class="modify_describe">所在地：</view>
        <view>
          <input type="text" name="userRegion" :value="userinfo.userRegion" placeholder="请输入所在地" />
        </view>
      </view>
      <button formType="submit" class="modify_button">保存</button>
    </form>
  </view>
</template>

<script>
  import {
    mapState,
    mapMutations
  } from 'vuex'
  export default {
    data() {
      return {
        avatarUrl: '',
        newUserInfo: {},
        //判断用户有没有更换头像的标志
        changeAvatarTag: false
      };
    },
    onLoad() {
      this.avatarUrl = this.userinfo.userAvatar
    },
    computed: {
      ...mapState('m_user', ['token', 'userinfo'])
    },
    methods: {
      ...mapMutations('m_user', ['updateUserInfo']),
      // 更换用户头像事件
      changeAvatar() {
        let that = this
        uni.chooseMedia({
          count: 1,
          mediaType: ['image'],
          sourceType: ['album', 'camera'],
          camera: 'back',
          success(res) {
            that.avatarUrl = res.tempFiles[0].tempFilePath
            that.changeAvatarTag = true
          }
        })
      },
      // 上传头像到服务器中
      uploadAvatarToServer() {
        const userID = this.userinfo.userID
        console.log('上传头像userID', userID)
        console.log('上传头像')
        uni.uploadFile({
          filePath: this.avatarUrl,
          name: 'image',
          url: 'https://jeoz.top:3000/api/uploadAvatar?userID=' + userID,
          success: res => {
            // console.log(res)
            console.log('上传成功')
          }
        })
        this.changeAvatarTag = false
      },

      // 获取 form 表单中的用户信息
      formSubmit(e) {
        const formData = e.detail.value
        const emailPattern = /^[\w.-]+@[a-zA-Z_-]+?(?:\.[a-zA-Z]{2,6})+$/ // 邮箱正则表达式验证格式
        const phoneNumberPattern = /^1[3|4|5|6|7|8|9]\d{9}$/ // 手机号正则表达式验证格式
        if (formData.userGender !== '男' && formData.userGender !== '女' && formData.userGender !== '') {
          // 用户输入的性别格式不正确
          return uni.$showMsg('性别格式错误！')
        } else if (formData.userEmail !== '' && !emailPattern.test(formData.userEmail)) {
          // 用户输入的邮箱格式不正确
          return uni.$showMsg('邮箱格式错误！')
        } else if (formData.userPhoneNumber !== '' && !phoneNumberPattern.test(formData.userPhoneNumber)) {
          // 用户输入的手机号格式不正确
          return uni.$showMsg('手机号格式错误！')
        }

        this.newUserInfo = {
          userName: formData.userName,
          userGender: formData.userGender,
          userWeight: formData.userWeight,
          userBMI: formData.userBMI,
          userPhoneNumber: formData.userPhoneNumber,
          userRegion: formData.userRegion,
          userEmail: formData.userEmail,
        }

        // 获取用户授权信息
        this.getUserProfile()
      },
      // 获取用户授权信息
      getUserProfile() {
        let that = this
        uni.getUserProfile({
          desc: '你的授权信息',
          success: (res) => {
            //上传头像
            console.log('this.changeAvatar',that.changeAvatar)
            if(that.changeAvatarTag === true) {
              this.uploadAvatarToServer()
            }
            //上传用户信息
            this.updateServerUserInfo(res)
            // 返回到上一个页面
            uni.navigateBack()
          },
          fail: (res) => {
            return uni.$showMsg('您取消了登录授权')
          }
        })
      },

      //用户像后端发送请求修改更新用户信息数据
      async updateServerUserInfo(info) {
        const [err, res] = await uni.login().catch(err => err)
        if (err || res.errMsg !== 'login:ok') return uni.$showMsg('登录失败！')
        // 准备参数
        const query = {
          newUserInfo: this.newUserInfo,
          code: res.code,
          encryptedData: info.encryptedData,
          iv: info.iv,
          rawData: info.rawData,
          signature: info.signature
        }
        const {
          data: modifyResult
        } = await uni.$http.post('/api/modify/userInfo', query)
        console.log('后端返回的登录数据modifyResult', modifyResult)
        if (modifyResult.meta.status === 404) {
          uni.$showMsg('修改失败！')
          return
        } else if (modifyResult.meta.status === 200) {
          // 将 token 保存到 vuex 中
          console.log(modifyResult.message.userInfo)
          //获取用户信息后更新userInfo
          this.updateUserInfo(modifyResult.message.userInfo)
        }
      },
    }
  }
</script>

<style lang="scss">
  .my_modify {
    width: 675rpx;
    margin: 50rpx auto 10rpx auto;
    border-radius: 15rpx;
    box-shadow: 0px 0.5px 4px 0.1px #f7f9ff;

    .modify_container {
      flex-direction: row;
      align-items: center;
      justify-content: center;
      padding: 20rpx 20rpx 20rpx 35rpx;
      line-height: 60rpx;
      border-bottom: 1px solid #efefef;
      height: 60rpx;
      background-color: #fff;
    }

    .modify_describe {
      line-height: 60rpx;
      height: 60rpx;
      float: left;
    }

    .modify_img {
      height: 60rpx;
      display: flex;
      align-items: center;

      image {
        width: 50rpx;
        height: 50rpx;
      }
    }

    input {
      line-height: 60rpx;
      height: 60rpx;
      font-size: 28rpx;
    }

    .modify_button {
      width: 675rpx;
      color: white;
      margin-top: 20rpx;
      font-size: 30rpx;
      background-color: #fba007;
    }
  }
</style>